package dao;

import com.sun.org.apache.xpath.internal.operations.Bool;
import db.MysqlDB;
import vo.Book;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDao {
    public List<Book> getAll(){
        MysqlDB db=new MysqlDB();
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        List<Book> list=new ArrayList();
        try {
            conn=db.getConn();
            ps=conn.prepareStatement("select * from t_book");
            rs=ps.executeQuery();
            while (rs.next()){
                Book book=new Book();
                book.setBook_number(rs.getString(1));
                book.setBook_name(rs.getString(2));
                book.setAothor(rs.getString(3));
                book.setPublisher(rs.getString(4));
                book.setPrice(rs.getFloat(5));
                list.add(book);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                db.closeAll(conn,ps,rs  );
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;

    }

    public boolean insert(Book book){
        MysqlDB db=new MysqlDB();
        Connection conn=null;
        PreparedStatement ps=null;
        conn=db.getConn();
        int i=0;
        try {
            ps=conn.prepareStatement("insert into t_book values(?,?,?,?,?)");
            Book b=book;
            ps.setString(1,b.getBook_number());
            ps.setString(2,b.getBook_name());
            ps.setString(3,b.getAothor());
            ps.setString(4,b.getPublisher());
            ps.setFloat(5,b.getPrice());
            i=ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                db.closeAll(conn,ps,null);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return i>0;
    }
}
